package com.filex.ads.network;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;


import com.filex.ads.common.Preconditions;
import com.filex.ads.volley.NetworkResponse;
import com.filex.ads.volley.Request;
import com.filex.ads.volley.Response;
import com.filex.ads.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public abstract class FilexRequest<T> extends Request<T> {

    private static final String JSON_CONTENT_TYPE = "application/json; charset=UTF-8";

    @NonNull
    private final String mOriginalUrl;
    @NonNull
    private final Context mContext;

    public FilexRequest(@NonNull final Context context,
                        @NonNull final String url,
                        @Nullable final Response.ErrorListener listener) {
        super(AdRequestUtils.chooseMethod(url), AdRequestUtils.truncateQueryParamsIfPost(url),
                listener);

        mOriginalUrl = url;
        mContext = context.getApplicationContext();
    }

    @Override
    protected Map<String, String> getParams() {
        if (!AdRequestUtils.isFilexRequest(getUrl())) {
            return null;
        }

        return AdRequestUtils.convertQueryToMap(mContext, mOriginalUrl);
    }

    @Override
    public String getBodyContentType() {
        if (AdRequestUtils.isFilexRequest(getUrl())) {
            return JSON_CONTENT_TYPE;
        }
        return super.getBodyContentType();
    }

    @Override
    public byte[] getBody() {
        final String body = AdRequestUtils.generateBodyFromParams(getParams(), getUrl());
        if (body == null) {
            return null;
        }
        return body.getBytes();
    }

    @NonNull
    protected String parseStringBody(@NonNull final NetworkResponse response) {
        Preconditions.checkNotNull(response);

        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return parsed;
    }

    @NonNull
    public String getOriginalUrl() {
        return mOriginalUrl;
    }

}
